package h;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import d.Json;

import b.Entity;

@SuppressWarnings("serial")
public class DataServlet extends HttpServlet {
	public static Pattern uriPattern;

	@Override
	public void init(){
		uriPattern = Pattern.compile("^"+this.getServletContext().getContextPath()+"/srv/(\\w+)/(.+)$");
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
		boolean implemented=true;
		Matcher m = uriPattern.matcher(request.getRequestURI());
		if(m.matches()) {
			try {
				Class<?> c = Class.forName("b."+m.group(1));
				String[] args = m.group(2).split("/");
				
				if(args[0].equals("retrieve")) {
					Entity e = (Entity) c.getDeclaredMethod("retrieve",int.class).invoke(null, Integer.parseInt(args[1]));

					response.setContentType("text/plain");
					response.getWriter().print(Json.toJsonString(e));
				} else {
					implemented = false;
				}
			} catch (Exception e) {
				implemented = false;
			}
		} else {
			implemented = false;
		}
		
		if(!implemented) {
			response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
		}
	}
	
	public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
		doPost(request,response);
	}
}
